using System;
using Quiki.ExpressionParsers;
using Quiki.Templates;

namespace Quiki.DocumentPostprocessors
{
    public class DocumentTitleInserter : IDocumentPostprocessor
    {
        public void PostProcessDocument(WikiDocument document)
        {
            if (AlreadyHasTitle(document))
                return;

            InsertTitle(document);
        }

        private static bool AlreadyHasTitle (WikiDocument document)
        {
            return null != document.RootElement.FindElement (
               x => x.ElementType == WikiTextElementType.Template
                && ((WikiTemplateElement)x).TemplateName == TitleTemplate.TemplateId);
        }

        private static void InsertTitle(WikiDocument document)
        {
            WikiTemplateElement templateElement = new WikiTemplateElement (
                TitleTemplate.TemplateId,
                document.Title);
            document.RootElement.ChildElements.Insert (0, templateElement);
        }
    }
}